// pages/Payment/Payment.js
var app = getApp()
const $api = require('../../utils/api.js').API;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件所需的参数
    navbarData: {
      havebg: 1, //1表示不显示    0表示显示
      out: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '详情', //导航栏 中间的标题
      bg: '#fff', //导航背景
    },
    imglist: [],
    payType: '',
    lookType: 1,
    paylist: [{}],
    height: app.globalData.height,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var user_address = wx.getStorageSync('address')
    console.log(options)

    let _this = this
    let navbarData = _this.data.navbarData
    navbarData.out = options.upType ? 1 : 0

    _this.setData({ navbarData, lookType: options.lookType ? options.lookType : 1 })
    if (options.lookType == 3) {
      $api.getuserinfo({
        login_token: wx.getStorageSync('login_token'),
      }).then((res) => {

        let rzinfo = {
          user_name: res.data.data.sm_user_name,
          user_name_Type: res.data.data.sm_user_name ? true : false,
          mobile: res.data.data.sm_mobile,
          mobile_Type: res.data.data.sm_mobile ? true : false,
          id_card: res.data.data.sm_idcard,
          id_card_Type: res.data.data.sm_idcard ? true : false,
        }
        _this.setData({
          rzinfo,
          lookTypeOc: res.data.data.sm_user_name ? true : false,
          member_id: res.data.data.member_id,
          mt: true
        })
      }).catch((err) => {
        _this.setData({
          loadModal: false,

        })
      })
    }
    if (options.order_id) {
      $api.getpaymethodfinal({
        login_token: wx.getStorageSync('login_token'),
        order_id: options.order_id
      }).then((res) => {
        console.log(res)
        let list = res.data.data.pay_lists
        let xxzfType = ''
        let payList = []
        list.forEach((item) => {
          if (item.type == 'xxzf') {
            xxzfType = item.status
          }
          // && item.type != 'ysf'
          if (item.type != 'zfb' && item.type != 'wx' && item.type != 'sfzfb' && item.type != 'ysf') {
            payList.push(item)
          }
        })
        payList.forEach((item, index) => {
          item.index = index + 1
        })
        console.log(payList)
        _this.setData({ xxzfType, open_bank: res.data.data.open_bank, payType: '', payIndex: '', payList, user_shop_info: res.data.data.user_shop_info, xcx_yc_pay: res.data.data.xcx_yc_pay })

      })
      this.setData({ order_id: options.order_id, upType: options.upType, })
    }

  },
  paytap(e) {
    this.setData({ payType: e.currentTarget.dataset.type, type_cid: e.currentTarget.dataset.typecid, payIndex: e.currentTarget.dataset.index })
  },
  chooseImage: function () {
    let _this = this
    let imglist = _this.data.imglist
    $api.uploadImagesdt(true).then((res) => {
      let info = res
      info.forEach((item) => {
        imglist.push(item.url)
      })
      _this.setData({ imglist })
    })
  },
  onCloseImgs(e) {
    let imglist = this.data.imglist
    imglist.splice(e.currentTarget.dataset.index, 1)
    console.log(imglist)
    this.setData({ imglist })
  },
  goPay() {
    let _this = this
    if (!_this.data.payIndex) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
        duration: 2000
      })
      return
    }
    _this.setData({
      loadModal: true
    })

    if (_this.data.payType == 'sfwx' || _this.data.payType == 'ysf') {
      var user_address = wx.getStorageSync('address')
      //支付
      wx.login({
        success(res) {
          console.log(res)
          $api.getOpenidAppPay({
            js_code: res.code
          }).then((res) => {
            console.log(res.data, 66)
            if (res.data.code == 0) {
              var openid = res.data.data.openid;
              $api.appPayFunc({
                login_token: wx.getStorageSync('login_token'),//用户登录token
                order_id: _this.data.order_id,//订单id
                pay_type: _this.data.payType == 'xcx_yc_pay' ? 1 : _this.data.payType == 'sfwx' ? 4 : _this.data.payType == 'ysf' ? 8 : '',//支付类型 4 第三方微信支付  8 云闪付
                is_fp: 0,//是否分批付款 0否 1是
                // fp_money: options.fp_money,//付款金额
                sf_openid: openid,//三方支付微信支付的openid

              }).then((res) => {
                _this.setData({ loadModal: false })
                if (res.data.code == 0) {
                  if (_this.data.payType == 'sfwx') {
                    var payData = JSON.parse(res.data.data.sfwxdata.expend.pay_info);
                    var packages = payData.package;
                    var timeStamp = payData.timeStamp;
                    wx.requestPayment({
                      timeStamp: timeStamp.toString(),
                      nonceStr: payData.nonceStr,
                      package: packages,
                      signType: payData.signType,
                      paySign: payData.paySign,
                      success(res) {
                        console.log(res)
                        //支付成功
                        wx.removeStorageSync('address')
                        wx.redirectTo({
                          url: '/pages/order/order?type=4',
                        })
                      },
                      fail(res) {
                        console.log(res)
                        wx.redirectTo({
                          url: '/pages/order/order?type=4',
                        })
                      },
                      complete() {
                        wx.removeStorageSync('userAddressData');
                        wx.removeStorageSync('giftId');
                        wx.removeStorageSync('wait_pay');
                        wx.removeStorageSync('applyShop');
                        wx.removeStorageSync('pay');
                        wx.removeStorageSync('goodsList');
                        wx.removeStorageSync('default_lb_num');
                        wx.removeStorageSync('giftnumber');
                        wx.removeStorageSync('statusReading');
                        wx.removeStorageSync('UpLevelType');
                        wx.removeStorageSync('faultnum');
                        wx.removeStorageSync('imglist');
                        wx.removeStorageSync('pzimg');
                        wx.removeStorageSync('giftInfoList');
                      }
                    })
                  } else if (_this.data.payType == 'ysf') {
                    wx.showToast({
                      title: '支付失败请更换支付方式',
                      icon: 'none',
                      duration: 2000
                    })
                  } else if (_this.data.payType == 'xcx_yc_pay') {
                    let data = res.data.data.wxdata
                    console.log(data)
                    wx.requestPayment({
                      timeStamp: data.timestamp.toString(),
                      nonceStr: data.noncestr,
                      package: data.package,
                      signType: 'MD5',
                      paySign: data.sign,
                      success(res) {
                        console.log(res)
                        //支付成功
                        wx.removeStorageSync('address')
                        wx.redirectTo({
                          url: '/pages/order/order?type=4',
                        })
                      },
                      fail(res) {
                        console.log(res)
                        wx.redirectTo({
                          url: '/pages/order/order?type=4',
                        })
                      },
                      complete() {
                        wx.removeStorageSync('userAddressData');
                        wx.removeStorageSync('giftId');
                        wx.removeStorageSync('wait_pay');
                        wx.removeStorageSync('applyShop');
                        wx.removeStorageSync('pay');
                        wx.removeStorageSync('goodsList');
                        wx.removeStorageSync('default_lb_num');
                        wx.removeStorageSync('giftnumber');
                        wx.removeStorageSync('statusReading');
                        wx.removeStorageSync('UpLevelType');
                        wx.removeStorageSync('faultnum');
                        wx.removeStorageSync('imglist');
                        wx.removeStorageSync('pzimg');
                        wx.removeStorageSync('giftInfoList');
                      }
                    })
                  }


                } else {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          })
        }
      })
    } else if (_this.data.payType == 'xxzf') {
      if (_this.data.imglist.length == 0) {
        wx.showToast({
          title: '请上传付款凭证',
          icon: 'none',
          duration: 2000
        })
        _this.setData({
          loadModal: false
        })
        return
      }
      var user_address = wx.getStorageSync('address')
      $api.underlinePay({
        login_token: wx.getStorageSync('login_token'),//用户登录token
        order_id: _this.data.order_id,//订单id
        fukuan_imgs: JSON.stringify(_this.data.imglist)

      }).then((res) => {
        if (res.data.code == 0) {
          wx.redirectTo({
            url: '/pages/order/order?type=4',
          })
          wx.removeStorageSync('userAddressData');
          wx.removeStorageSync('giftId');
          wx.removeStorageSync('wait_pay');
          wx.removeStorageSync('applyShop');
          wx.removeStorageSync('pay');
          wx.removeStorageSync('goodsList');
          wx.removeStorageSync('default_lb_num');
          wx.removeStorageSync('giftnumber');
          wx.removeStorageSync('statusReading');
          wx.removeStorageSync('UpLevelType');
          wx.removeStorageSync('faultnum');
          wx.removeStorageSync('imglist');
          wx.removeStorageSync('pzimg');
          wx.removeStorageSync('giftInfoList')
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else if (_this.data.payType == 'sfyhk') {
      let user_bank_id = ''
      let tel = ''
      _this.data.payList.forEach((item) => {
        if (item.index == _this.data.payIndex) {
          user_bank_id = item.user_bink_id
          tel = item.tel_no
        }
      })
      $api.appPayFunc({
        login_token: wx.getStorageSync('login_token'),//用户登录token
        order_id: _this.data.order_id,//订单id
        pay_type: 6,//支付类型 6 银行卡支付
        is_fp: 0,//是否分批付款 0否 1是
        // fp_money: options.fp_money,//付款金额
        user_bank_id: user_bank_id,//用户绑定银行卡id

      }).then((res) => {
        if (res.data.code == 0) {
          wx.redirectTo({
            url: '/pages/Payment/phone?add=2&orderid=' + _this.data.order_id + '&upType=' + _this.data.upType + '&mobile=' + tel,
          })
          _this.setData({ loadModal: false })

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else if (_this.data.payType == 'xcx_yc_pay') {
      wx.login({
        success(res) {
          console.log(res)
          $api.getOpenidAppPay({
            js_code: res.code
          }).then((res) => {
            console.log(res.data, 66)
            if (res.data.code == 0) {
              var openid = res.data.data.openid;
              $api.wxPay({
                login_token: wx.getStorageSync('login_token'),
                order_id: _this.data.order_id,
                openid: openid
              }).then((res) => {
                var wxPay = res.data.data;
                var timeStamp = wxPay.timeStamp
                wx.requestPayment({
                  timeStamp: timeStamp.toString(),
                  nonceStr: wxPay.nonceStr,
                  package: wxPay.package,
                  signType: wxPay.signType,
                  paySign: wxPay.paySign,
                  success(res) {
                    _this.setData({
                      loadModal: false
                    })
                    wx.redirectTo({
                      url: '/pages/order/order?type=4',
                    })
                  },
                  fail(res) {
                    console.log(res)
                    _this.setData({
                      loadModal: false
                    })
                    wx.redirectTo({
                      url: '/pages/order/order?type=4',
                    })
                  }
                })
              }).catch((err) => {
                _this.setData({
                  loadModal: false
                })
              })
            }
          })
        }
      })

    }
  },
  addpay() {
    let _this = this
    $api.getuserinfo({
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      if(!res.data.data.member_id){
        let rzinfo = {
          user_name: res.data.data.sm_user_name,
          user_name_Type: res.data.data.sm_user_name ? true : false,
          mobile: res.data.data.sm_mobile,
          mobile_Type: res.data.data.sm_mobile ? true : false,
          id_card: res.data.data.sm_idcard,
          id_card_Type: res.data.data.sm_idcard ? true : false,
        }
        _this.setData({
          rzinfo,
          lookTypeOc: res.data.data.sm_user_name ? true : false,
          member_id: res.data.data.member_id,
          lookType:3,
        })
      }else{
        _this.getbanks()
        _this.setData({ lookType: 2 })
      }
      
    }).catch((err) => {
      _this.setData({
        loadModal: false,

      })
    })
    // if (_this.data.user_shop_info.status == 0 && !_this.data.user_shop_info.sm_info.sm_idcard) {
    //   _this.setData({ lookType: 3, rzinfo: {} })
    // } else {
    //   _this.getbanks()
    //   _this.setData({ lookType: 2 })
    // }

  },
  // 银行卡列表
  getbanks() {
    let _this = this
    $api.getbanks({
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      console.log(res)
      _this.setData({ banklist: res.data.data })
    })
  },
  //选择银行卡弹出
  onBankModal(e) {
    var _this = this;
    if (e.currentTarget.dataset.id) {
      _this.setData({
        bankid: e.currentTarget.dataset.id,
        bank_name: e.currentTarget.dataset.bank_name
      })
    }
    _this.setData({
      //   bankStatus: 0,
      //   status: 0,
      modalName: e.currentTarget.dataset.target,
      //   banknum: '',
      //   bankphone: '',
      //   banktime: '',
      //   bankphone: '',
    })
  },
  //选择银行卡类型
  onBankStatus(e) {
    var status = e.currentTarget.dataset.status;
    this.setData({
      status: status
    })
  },
  //选择银行卡---确定
  onBankDetermine(e) {
    var _this = this;
    _this.setData({
      bankStatus: _this.data.status,
      modalName: null
    })
  },
  //获取银行卡卡号
  onBankNum(e) {
    this.setData({
      banknum: e.detail.value
    })
  },
  //获取预留手机号
  onBankPhone(e) {
    this.setData({
      bankphone: e.detail.value
    })
  },
  //获取信用卡校检码
  onBankVipCode(e) {
    this.setData({
      bankcode: e.detail.value
    })
  },
  //获取信用卡有效期
  onBankTime(e) {
    var time = e.detail.value;
    var yy = time.substring(2, 4);
    var mm = time.substring(5, 7);
    this.setData({
      banktime: mm + ' / ' + yy,
      banktimees: mm + yy
    })
  },
  // 下一步
  onNext() {
    var _this = this;
    var bankStatus = _this.data.bankStatus; //银行卡类型
    var banknum = _this.data.banknum; //银行卡卡号
    var bankphone = _this.data.bankphone; //预留手机号
    var bankcode = _this.data.bankcode; //信用卡校检码
    var banktimees = _this.data.banktimees; //信用卡有效期
    console.log(banktimees)
    if (bankStatus == 1) {
      //储蓄卡
      if (banknum == '') {
        wx.showToast({
          title: '请输入银行卡卡号',
          icon: 'none',
          duration: 2000
        })
      } else if (bankphone == '') {
        wx.showToast({
          title: '请输入银行预留手机号',
          icon: 'none',
          duration: 2000
        })
      } else if (!(/^1[3456789]\d{9}$/.test(bankphone))) {
        wx.showToast({
          title: '请输入正确的手机号码',
          icon: 'none',
          duration: 2000
        })
      } else {
        if (bankStatus == 2) {
          if (!bankcode) {
            wx.showToast({
              title: '请输入信用卡验证码',
              icon: 'none',
              duration: 2000
            })
            return
          }
          if (!banktimees) {
            wx.showToast({
              title: '请选择信用卡有效期',
              icon: 'none',
              duration: 2000
            })
            return
          }
        }
        _this.setData({ loadModal: true })
        //获取添加银行卡的验证码
        $api.addUserBank({
          login_token: wx.getStorageSync('login_token'),//用户登录token
          bank_id: _this.data.bankid,//银行卡id
          type: bankStatus,//银行卡类型 1 借记卡 2 信用卡
          card_id: banknum,//银行卡卡号
          tel_no: bankphone,//银行卡预留的手机号
          vip_code: bankcode ? bankcode : '',//信用卡验证码（如果类型为信用卡，则该项必填
          expiration: banktimees ? banktimees : '',//信用卡有效期（如果类型为信用卡，则该项必填）
        }).then((res) => {
          if (res.data.code == 0) {
            wx.redirectTo({
              url: '/pages/Payment/phone?apply_id=' + res.data.data + '&bank_type=' + _this.data.bankid + '&tel=' + bankphone + '&card_id=' + banknum + '&type=' + bankStatus + '&add=1&orderid=' + _this.data.order_id + '&upType=' + _this.data.upType,
            })
            _this.setData({ loadModal: false })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
            _this.setData({ loadModal: false })
          }
        })
      }
    }
  },
  onrz(e) {
    let rzinfo = this.data.rzinfo
    let data = e.detail.value
    let rztype = e.currentTarget.dataset.rztype
    rzinfo[rztype] = data
    this.setData({
      rztype
    })
  },
  sm_auth() {
    let _this = this
    let rzinfo = _this.data.rzinfo
    if (!rzinfo.user_name || !rzinfo.mobile || !rzinfo.id_card) {
      wx.showToast({
        title: '请将认证信息填写完整',
        icon: 'none',
        duration: 2000
      })
      return
    }
    $api.smauth({
      login_token: wx.getStorageSync('login_token'),//用户登录token
      user_name: rzinfo.user_name,
      mobile: rzinfo.mobile,
      id_card: rzinfo.id_card,
    }).then((res) => {
      if (res.data.code == 0) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
        if (_this.data.mt) {
          _this.out()
        } else {
          _this.getbanks()
          _this.setData({ loadModal: false, lookType: 2 })
        }

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
        _this.setData({ loadModal: false })
      }
    })
  },
  //返回上一页
  out() {
    wx.navigateBack({
      delta: 1,
    })
  },
})